package com.cppba.alipay.controller;

import com.cppba.alipay.bizcontent.AlipayTradePagePayBizContent;
import com.cppba.alipay.properties.AlipayProperties;
import com.cppba.alipay.request.AlipayTradePagePayRequest;
import com.cppba.alipay.util.MoneyUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.Random;

/**
 * 统一收单下单并支付页面接口
 *
 * @author winfed
 * @create 2017-10-23 15:32
 */
@Controller
@RequestMapping("/alipay")
public class AlipayTradePagePayController {

    private final AlipayProperties alipayProperties;

    @Autowired
    public AlipayTradePagePayController(AlipayProperties alipayProperties) {
        this.alipayProperties = alipayProperties;
    }

    /**
     * 发起网站支付
     *
     * @return 跳到支付页面
     */
    @RequestMapping(value = "/trade/page/pay", produces = MediaType.TEXT_HTML_VALUE)
    @ResponseBody
    public String alipayTradePagePay() {
        // http://127.0.0.1:8080/alipay/trade/page/pay
        // 模拟数据
        String serialNumber = "No" + new Random(new Date().getTime()).nextInt();
        String title = "测试订单title";
        String body = "测试订单body";
        Long orderAmount = 100L;
        // 业务参数
        AlipayTradePagePayBizContent alipayTradePagePayBizContent = new AlipayTradePagePayBizContent();
        alipayTradePagePayBizContent.setOutTradeNo(serialNumber);
        alipayTradePagePayBizContent.setBody(body);
        alipayTradePagePayBizContent.setSubject(title);
        alipayTradePagePayBizContent.setTotalAmount(MoneyUtils.getMoney(orderAmount).toString());
        alipayTradePagePayBizContent.setProductCode("FAST_INSTANT_TRADE_PAY");
        alipayTradePagePayBizContent.setTimeoutExpress(alipayProperties.getTimeoutExpress());
        // alipayTradePagePayBizContent.setExtendParams(new AlipayTradePagePayBizContent.ExtendParams());
        // 请求构建对象
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest(alipayProperties.getIsTest(), alipayProperties.getAppId(), alipayProperties.getPrivateKey(), alipayProperties.getAlipayPublicKey(),
                alipayProperties.getSignType(), alipayTradePagePayBizContent, alipayProperties.getNotifyUrl(), null);
        // 构建html返回页面
        return alipayTradePagePayRequest.createResposeHtml();
    }
}
